<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="businessName">
              <el-input v-model="filters.businessName" clearable placeholder="商户名称"></el-input>
            </el-form-item>
            <el-form-item prop="businessShortName">
              <el-input v-model="filters.businessShortName" clearable placeholder="商户简称"></el-input>
            </el-form-item>
            <el-form-item prop="businessType">
              <el-select v-model="filters.businessType" clearable placeholder="商户类型">
                <el-option v-for="item in businessTypeList" :key="item.value" :value="item.value" :label="item.label"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="manageType">
              <el-select v-model="filters.manageType" clearable filterable placeholder="经营方式">
                <el-option v-for="item in manageList" :value="item.value" :label="item.label" :key="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="linkName">
              <el-input v-model="filters.linkName" clearable placeholder="联系人"></el-input>
            </el-form-item>
            <el-form-item prop="linkPhone">
              <el-input v-model="filters.linkPhone" clearable placeholder="联系电话"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table ref="table" :data="dataList" :fit="true" highlight-current-row v-loading="listLoading" element-loading-text="数据加载中，请稍后..." empty-text="对不起，没有找到相关数据！">
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column align="center" label="商户Logo" width="120">
          <template slot-scope="scope">
            <el-image title="点击可预览" :src="scope.row.businessLogo" fit="cover" :preview-src-list="[scope.row.businessLogo]" :z-index="scope.$index"> </el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" label="商户名称" prop="businessName"> </el-table-column>
        <el-table-column align="center" label="商户简称" prop="businessShortName"> </el-table-column>

        <el-table-column align="center" label="商户类型">
          <template slot-scope="scope">
            <div>
              {{ formatBusinessType(scope.row.businessType) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="经营方式">
          <template slot-scope="scope">
            <span>{{ scope.row.manageType == 1 ? '自运营' : '托管平台运营' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="联系人" prop="linkName"> </el-table-column>
        <el-table-column align="center" label="联系电话" prop="linkPhone"> </el-table-column>
        <el-table-column align="center" label="联系地址">
          <template slot-scope="scope">
            <div>
              {{ linkAddress(scope.$index) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="商户状态">
          <template slot-scope="scope">
            <div>
              <el-tag size="mini" effect="dark" :type="formatBusinessStates(scope.row.businessState)">
                {{ formatBusinessState(scope.row.businessState) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="创建时间" prop="createDate"> </el-table-column>
        <el-table-column label="操作" width="136" fixed="right">
          <template slot-scope="scope">
            <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
            <el-button v-has="permissionRoleChange" v-if="scope.row.businessState > 0" @click="handleClickLogin(scope.row)" size="mini">跳转</el-button>
            <!--<el-dropdown trigger="click" size="small">
              <el-button type="primary">
                <i class="fa fa-list-ul"></i>更多
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="scope.row.businessState" v-has="permissionRoleChange" @click.native="handleClickLogin(scope.row)">切换角色
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>-->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具条 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>
  </div>
</template>
<script>
import BusinessApi from '@/api/business/business';
import GoodsApi from '@/api/goods/goods';
import * as message from '@/constants/message';
import AssoicateBusiness from '@/components/assoicateBusiness';
import { mapActions } from 'vuex';
import LoginApi from '@/api/system/login';
import * as stn from '../../constants/storeName';
import { setStorage, removeStorage, removeToken, setLocalStorage } from '@/utils/auth';
export default {
  name: 'BusinessManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      dataList: [],
      imgList: [],
      listLoading: true,
      filters: {
        businessName: '',
        businessShortName: '',
        businessType: '',
        manageType: '',
        linkName: '',
        linkPhone: '',
      },
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      // 商户类型列表
      businessTypeList: [
        { value: 1, label: '大众' },
        { value: 2, label: '专属' },
      ],
      manageList: [
        { value: 1, label: '自运营' },
        { value: 2, label: '托管平台运营' },
      ],

      permissionCheck: 'SYSTEM_MANAGER_BUSINESS_ASSOICATE_LIST_SEE',
      permissionRoleChange: 'SYSTEM_MANAGER_BUSINESS_ASSOICATE_LIST_ROLECHANGE',
    };
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    this.listData();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  components: {
    AssoicateBusiness,
  },
  watch: {
    //to去哪，from从哪来
    // $route(to,from){
    //   if(from.path =='/equip/specimenEdit' || from.path=='/equip/specimenAdd'){
    //       this.listData();
    //   }
    // }
  },
  methods: {
    ...mapActions({
      setToken: 'setToken',
    }),
    init() {
      let _this = this;
      _this.listLoading = true;
      _this.listData();
      _this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },

    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    // 把省市区和详细地址合并起来为联系地址
    linkAddress(index) {
      let prevAddress = this.dataList[index].provinceName + this.dataList[index].cityName + this.dataList[index].areaName;
      let streetName = this.dataList[index].streetName ? this.dataList[index].streetName : '';
      let address = this.dataList[index].address ? this.dataList[index].address : '';
      return prevAddress + streetName + address;
    },
    formatBusinessState(cellValue) {
      if (cellValue === 0) {
        return '未开通';
      } else if (cellValue === 1) {
        return '营业';
      } else if (cellValue === 2) {
        return '打烊';
      }
    },
    formatBusinessStates(cellValue) {
      if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      } else if (cellValue === 2) {
        return 'warning';
      }
    },
    formatState(cellValue) {
      if (cellValue === -1) {
        return '删除';
      } else if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      }
    },
    formatStates(cellValue) {
      if (cellValue === -1) {
        return 'danger';
      } else if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    formatBusinessType(cellValue) {
      if (cellValue === 1) {
        return '大众';
      } else if (cellValue === 2) {
        return '专属';
      }
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listData();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listData();
    },
    handleClickAdd() {
      let _this = this;
      _this.$router.push('/business/businessAdd');
    },
    handleClickDetail(row) {
      let _this = this;
      _this.$router.push({
        path: '/business/businessDetail',
        query: { id: row.businessId },
      });
    },
    handleClickLogin(row) {
      // return
      this.$confirm('是否确定切换角色?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        // this.$store.dispatch('LogOut').then(() => {
        // 清两次，避免报token错误
        // location.reload()// In order to re-instantiate the vue-router object to avoid bugs
        let params = {
          userRole: 3,
          relationId: row.businessId,
        };
        // 快捷登录
        LoginApi.fastLogin(params).then((res) => {
          removeStorage(stn.LOGIN_STATUS);
          removeStorage(stn.USER_INFO);
          removeStorage(stn.MENU_LIST);
          removeStorage(stn.MENUS_PERMISSION);
          removeToken();
          let data = res.data;
          localStorage.setItem('isToken', data.token);
          this.setToken(data.token);
          setStorage(stn.MENU_LIST, data.menuList);
          setStorage(stn.USER_RELATION, data.userRelation);
          setLocalStorage(stn.ROLE_CHANGE, 1);
          sessionStorage.setItem('isNotify', 'false');
          this.$store.commit('SET_ROLES', []);

          // this.$router.push("/");
          // setTimeout(()=>{
          location.reload();
          // },200)
        });

        // })
      });
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch();
    },
    onSearch() {
      this.listLoading = true;
      this.page.pageNo = 1;
      this.listData();
    },
    listData() {
      // 获取列表数据
      let _this = this;
      let cond = {
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize,
      };
      cond.linkName = _this.filters.linkName;
      cond.linkPhone = _this.filters.linkPhone;
      cond.businessType = _this.filters.businessType;
      cond.businessName = _this.filters.businessName;
      cond.businessShortName = _this.filters.businessShortName;
      cond.manageType = _this.filters.manageType;
      BusinessApi.listBusiness(cond)
        .then((res) => {
          _this.dataList = res.data.list;
          _this.page.pageTotal = res.data.total;
          _this.listLoading = false;
          _this.$refs.table.bodyWrapper.scrollTop = 0;
        })
        .catch((err) => {
          _this.listLoading = false;
        });
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
